<!-- @format -->

<template>
	<view class="l-switch" @click="onchange">
		<view :class="[`l-switch-content-${size}`]" :style="bgStyle">
			<view class="l-switch-content-core" :class="[`l-switch-content-core-${!value ? 'close' : loading ? 'loading' : 'open'}`]"></view>
		</view>
	</view>
</template>

<script>
	import props from "./props.js";
	export default {
		name: "l-switch",
		mixins: [props],
		data() {
			return {};
		},
		methods: {},
		computed: {
			bgStyle() {
				const style = {
					background: this.value ? this.activeColor : this.inactiveColor,
					opacity: this.disabled && 0.5,
				};
				return uni.$lu.addStyle(style);
			},
		},
		methods: {
			// 打开关闭的事件
			onchange() {
				// 当禁用时则不触发change事件
				if (this.disabled || (this.loading && this.value)) return;
				this.$emit("change", this.value);
			},
		},
	};
</script>

<style lang="scss" scoped>
	$arrSize: (
		(
			size: "normal",
			width: 40px,
			heigth: 15px,
		),
		(
			size: "medium",
			width: 50px,
			heigth: 20px,
		),
		(
			size: "large",
			width: 60px,
			heigth: 25px,
		)
	);

	@for $i from 1 through length($arrSize) {
		$item: nth($arrSize, $i);

		.l-switch-content-#{map-get($item,size)} {
			display: flex;
			align-items: center;
			width: map-get($item, width);
			height: map-get($item, heigth);
			border-radius: 10rem;
			padding: 5px;
			transition: all 0.3s ease;

			.l-switch-content-core {
				width: map-get($item, heigth);
				display: flex;
				justify-content: center;
				align-items: center;
				height: 100%;
				border-radius: 100%;
				background-color: white;
				transition: all 0.3s ease;
				position: relative;
			}
			
			.l-switch-content-core-open {
				transform: translateX(map-get($item, width) - map-get($item, heigth));
			}

			.l-switch-content-core-loading {
				transform: translateX(map-get($item, width) - map-get($item, heigth));
				position: relative;
			}

			.l-switch-content-core-loading::before {
				content: "";
				position: absolute;
				width: map-get($item, heigth) - 10;
				height: map-get($item, heigth) - 10;
				border-radius: 100%;
				border: 2px dotted rgba(0, 0, 0, 0.2);
				animation: rotate 2s linear infinite;
			}

			.l-switch-content-core-close {
				transform: translateX(0);
			}
		}
	}

	@keyframes rotate {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}
</style>
